<?php
/*
 * Created on 08.04.2008
 *
 * filename: model_user.php5
 * 
 */
 
 define ('MODEL_USER_FIND',					'SELECT * FROM `users` WHERE `id` = ? AND `type` = ? ');
 define ('MODEL_USER_FIND_ALL',				'SELECT * FROM `users` WHERE `type` = ? ');
 define ('MODEL_USER_FIND_BY_LOGIN',		'SELECT * FROM `users` WHERE `login` = ? AND `type` = ? ');
 define ('MODEL_USER_FIND_BY_EMAIL',		'SELECT * FROM `users` WHERE `email` = ? AND `type` = ? ');
 define ('MODEL_USER_FIND_BY_CODE', 		'SELECT * FROM `users` WHERE `confirmation_id` = ? AND `type` = ? ');

 define ('MODEL_USER_ADD',					'INSERT INTO `users` (`id` ,`login` ,`password`, `email` ,`added` , `realname`, `confirmation_id`, `type`, `phone`) VALUES ( NULL , ?, ?, ?, now(), ?, ?, ?, ?)');
 
 define ('MODEL_USER_CONFIRM_EMAIL', 		'UPDATE `users` SET `enabled` = 1,`confirmed` = 1 WHERE confirmation_id = ?');

 define ('MODEL_USER_UPDATE',				'UPDATE `users` SET `realname` = ?, `email` = ? WHERE `id` = ?');
 define ('MODEL_USER_CHANGE_PASSWORD',		'UPDATE `users` SET `password` = ? WHERE `id` = ?');
 
 define	('MODEL_USER_GET_FEEDS',			'SELECT `email` FROM `feeds`,`users` WHERE `feeds`.`user_id` = `users`.`id` AND `object` = ? ');
 define ('MODEL_USER_CHECK_FEED',           'SELECT * FROM `feeds` WHERE `user_id` =  ? AND `object` = ? ');
 
 define ('MODEL_USER_ADD_FEED',             'INSERT INTO `feeds` (object,user_id) VALUES (?, ?)');
 define ('MODEL_USER_DELETE_FEED',          'DELETE FROM `feeds` WHERE object = ? AND user_id = ?');
 
 define ('MODEL_USER_FIND_NEW',				'SELECT * FROM `users` WHERE `confirmed` = ? AND `type`= ? ');
 
 class Model_User extends Models_Base {
 	protected $_type; // 
 
 	public $realname;
 	public $email;
 	public $id;
 	public $login;

	protected $logged = null;
 		
 	protected $info;
 	private $password;
 
 	function __construct($id = null) {
 		parent::__construct(null);
 		$this->_type = 2;
 		if(!empty($id)) {
 			
 			$this->init($id);

 		} 		
 	}
 	
 	function init($id) {

 		$this->info 	= $this->find(array(id => $id));

		$this->realname = $this->info->realname;
		$this->email 	= $this->info->email;
		$this->password = $this->info->password;
		$this->id		= $this->info->id;
		$this->login	= $this->info->login;
		$this->phone	= $this->info->phone;
 	}
 	
 	
 	
 /*	function info() {
 		
 		if(empty($this->info) && !empty($this->name)) {
 			$this->info = $this->find($this->id);
 			$this->name = $this->info->name;
 			$this->email = $this->info->email;
 			$this->password = $this->info->password;
 		}
  		
 		return $this->info;
 	}
 	
 	function set($user) {
 		
 		if(empty($this->id))
 			$this->id = $user->id;
 			
 		$this->info = $user;
 		$this->name = $this->info->realname;
 		$this->email = $this->info->email;
 		$this->password = $this->info->password; 		
 	}*/
 	
 	function find($args) {

		$type = $this->_type ;
		
		if(isset($args[type]))
			$type = $args[type]; 

 		if(isset($args[id]))
 			return $this->getRow(MODEL_USER_FIND,array($args[id],$type));
 		else if(isset($args[email]))
 			return $this->getRow(MODEL_USER_FIND_BY_EMAIL,array($args[email],$type));
 		else if (isset($args[code]))
 			return $this->getRow(MODEL_USER_FIND_BY_CODE,array($args[code],$type));
 		else if(isset($args[login]))
 			return $this->getRow(MODEL_USER_FIND_BY_LOGIN,array($args[login],$type));
 		else if(isset($args[confirmed]))
 			return $this->getAll(MODEL_USER_FIND_NEW,array($args[confirmed],$type));
 	}
 	
 	function findAll() {
 		return $this->getAll(MODEL_USER_FIND_ALL,array($this->_type));
 	}
 	
 	function add($args) {

		if($this->find(array( login =>$args[new_user_name])))
			throw new UserException ('user_exists');

		if($this->find(array(email => $args[email])))
			throw new UserException ('email_exists');

		$this->checkInput($args);

		$confirmation_id = $this->generateConfirmationId($args[new_user_name]);

		$result = $this->insertRow(
			MODEL_USER_ADD,
			array(
				$args[new_user_name],
				md5(md5($args[password])),
				$args[email],
				$args[real_name],
				$confirmation_id,
				$this->_type,
				$args[phone],
			)
		);
		
/*
		
		$sth = $this->dbh->prepare(ADD_NEW_EXTERNAL_USER);
		
		$confirmation_id = $this->generateConfirmationId($args[new_user_name]);

		$result = $sth->execute(
			array(
				$args[new_user_name],
				md5(md5($args[password])),
				$args[email],
				$args[real_name],
				$confirmation_id,
			)
		);		
	*/
		return $result ? $confirmation_id : false;
 	}
 	
 	function confirmEmail($code) {
 		
 		if( empty( $code )) {
			throw new UserException ('empty_actiavtion_code');
		}		
//		$user = new Model_User();
		
		$result = $this->find(array(code => $code));

		if(empty($result))
			throw new UserException ('wrong_actiavtion_code');

		if ($result->confirmed)
			throw new UserException ('used_actiavtion_code');
		
		$sth = $this->dbh->prepare(MODEL_USER_CONFIRM_EMAIL);
		return $sth->execute(array($code));		
 	}
 	
	private function checkInput($args) {
		if(empty($args[new_user_name] )) {
			throw new UserException ('empty_login');
		}

		if( !empty($args[new_user_name] ) &&(strlen($args[new_user_name] ) < 3 || strlen($args[new_user_name] ) > 20 )) {
			throw new UserException ('wrong_login_length');
		}

		if(empty($args[password] )) {
			throw new UserException ('empty_password');
		}

		if(!empty($args[password] ) && (strlen($args[password] ) < 3 || strlen($args[password] ) > 20 )) {
			throw new UserException ('wrong_password_length');
		}

		if(empty($args[password2] )) {
			throw new UserException ('empty_second_password');
		}

		if($args[password2] != $args[password] ) {
			throw new UserException ('password_mismatch');	
		}
	
		if(empty($args[email] )) 
			throw new UserException ('empty_email');			

		if (!filter_var($args[email], FILTER_VALIDATE_EMAIL))
			throw new UserException ('not_valid_email');

	
		if(empty($args[real_name] )) 
			throw new UserException ('empty_real_name');			
	}
	
	private function generateConfirmationId($username) {
		return md5(time.$username);
	}	
	
	function login($username,$password) {

		$user = $this->find(array(login => $username));

		if(empty($user))
			throw new UserException ('wrong_pair_login_password');

		$this->init($user->id);

		if(!$this->info->enabled && !$this->info->confirmed)
			throw new UserException ('email_is_not_confirmed');
		
		if(!$this->info->enabled)
			throw new UserException ('user_blocked');
		
		if(!$this->checkPassword($password)) 
			throw new UserException ('wrong_pair_login_password');

		$session = new Model_Session();
		
		$SID = $session->create($this->id, $this->_type);
		
		$this->logged = true;
		
		return $SID;
		
	} 	
	
	function logout() {
		$session = new Model_Session();
		$session->delete();
	}
	
	protected function checkPassword($password) {
		return md5(md5($password)) === $this->password ? true : false;
	}
	
	function is_logged() {
		
error_log(" is logged run =".$this->logged."=");
		
		if(!isset($this->logged)) {
					
			$session = new Model_Session();	
		
			$logged_user = $session->get();
		
			if(!$logged_user) {
				$this->logged = false;
error_log("-- 1");				
				return false;
			} else if ($logged_user->type != $this->_type) {
				$this->logged = false;
error_log("-- 2");				
				return false;
			} else {
				$this->init($logged_user->user_id);
				$this->logged = true;
			}

		} 
		
		return $this->logged;

	}
	
	function updateUser($name, $email, $id) {
		
		if(empty($name))
			throw new UserException ('empty_real_name');
		
		if(empty($email))
			throw new UserException ('empty_email');
			
		if (!filter_var($email, FILTER_VALIDATE_EMAIL))
			throw new UserException ('not_valid_email');
			
		$sth = $this->dbh->prepare(MODEL_USER_UPDATE);
//print_r(array($name, $email, $id));		
		return $sth->execute(array($name, $email, $id));
		
	}
	
	function changePassword ($password, $password2, $id) {
		
		if(empty( $password ) || (strlen( $password ) < 3 || strlen( $password ) > 20 ))
			throw new UserException ('wrong_password_length');

		if( $password != $password2 )
			throw new UserException ('password_mismatch');
		
		$sth = $this->dbh->prepare(MODEL_USER_CHANGE_PASSWORD);
		return $sth->execute(array(md5(md5($password)), $id));			
		
	}
	
	function getFeeds($object) {
		return $this->getAll(MODEL_USER_GET_FEEDS,array($object));
	}
    
    function checkFeed($object) {
        return $this->getAll(MODEL_USER_CHECK_FEED,array($this->id,$object));
    }
    
    function addFeed($object) {
        $this->doExecute(MODEL_USER_ADD_FEED, array($object,$this->id));
    }
    
    function deleteFeed($object) {
        $this->doExecute(MODEL_USER_DELETE_FEED, array($object,$this->id));
    }
 	
 }
?>